<template>
  <div class="home">
    <!-- 面包屑 -->
    <mbx />
    <!-- 卡片区 -->
    <el-card class="mt16">
      <!-- 添加商品信息 -->
      <el-alert
        title="添加商品信息"
        type="info"
        center
        :closable="false"
        show-icon
      >
      </el-alert>
      <!-- 添加商品信息 -->
      <el-steps
        :active="active * 1"
        class="mt16"
        align-center
        finish-status="success"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        :model="goods"
        :rules="rules"
        ref="add"
        label-width="100px"
        class="demo-ruleForm"
      >
        <!-- tabs标签页切换 -->
        <el-tabs
          tab-position="left"
          class="mt16"
          @tab-click="next"
          v-model="active"
          :before-leave="beforeLeave"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="goods.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="goods.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="goods.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="goods.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="goods.goods_cat"
                :options="options"
                :props="props"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 全选框 -->
            <el-form>
              <el-form-item
                :label="item.attr_name"
                v-for="(item, index) in dongziyu"
                :key="index"
              >
                <el-checkbox-group v-model="item.attr_vals">
                  <el-checkbox
                    :label="ite"
                    v-for="(ite, ind) in item.attr_vals"
                    :key="ind"
                  ></el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <!-- 静态资源 -->
            <el-form>
              <el-form-item
                :label="item.attr_name"
                v-for="(item, index) in jingtaiziyuan"
                :key="index"
              >
                <el-input v-model="item.attr_vals"></el-input>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              action="http://www.ysqorz.top:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :headers="headers"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件,且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="goods.goods_introduce"></quill-editor>
            <el-button type="primary" class="mt16" @click="add">添加</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      active: '0', //用于切换的变量
      goods: {
        goods_name: '',
        goods_cat: [], //以为','分割的分类列表
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_introduce: '', //商品介绍
        pics: [], //存放照片的数组
        attrs: [] //商品的参数（数组），包含 `动态参数` 和 `静态属性`
      },
      rules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请输入商品分类', trigger: 'blur' }
        ]
      },
      options: [], //选择器的数据
      props: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      dongziyu: [], //动态资源的数据
      jingtaiziyuan: [], //静态资源的数据
      headers: {
        Authorization: sessionStorage.getItem('token')
      }
    }
  },
  mounted() {
    this.fenlei()
    // console.log('接受的参数', this.$route.query.row)
  },
  methods: {
    //  向下走
    async next() {
      console.log('下标', this.active)
      if (this.active == '1') {
        const res = await this.$API.getcanshulist(this.cateid)
        console.log('动态资源', res)
        res.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length > 0 ? item.attr_vals.split(',') : []
        })
        this.dongziyu = res
      }

      if (this.active == '2') {
        const res1 = await this.$API.getcanshulist(this.cateid, 'only')
        console.log('静态资源', res1)
        this.jingtaiziyuan = res1
      }
    },
    //切换标签之前触发的的钩子函数
    beforeLeave(newv, oldv) {
      console.log(newv, oldv)
      if (oldv === '0' && this.goods.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类')
        return false
      }
    },
    // 获取的分类参数列表
    async fenlei() {
      const res = await this.$API.getgoodslist()
      console.log('商品分类数据', res)
      this.options = res
      console.log(this.options)
    },
    // 级联选择器变化会触发
    handleChange() {
      console.log('这是数组中的数据', this.goods.goods_cat)
      if (this.goods.goods_cat.length !== 3) {
        this.goods.goods_cat = []
      }
    },
    // 处理图片预览
    handlePreview() {},
    // 处理移除图片
    handleRemove(val) {
      console.log('这是移除事件', val)
      const delfile = val.response.data.tmp_path
      const index = this.goods.pics.findIndex((item) => {
        item.pic == delfile
      })
      this.goods.pics.splice(index, 1)
      console.log('删除成功的图片', this.goods.pics)
    },
    // 监听图片上传成功
    handleSuccess(val) {
      console.log('成功', val)
      const picinfo = { pic: val.data.tmp_path }
      this.goods.pics.push(picinfo)
      console.log('这是上传成功的照片', picinfo, this.goods.pics)
    },
    // 添加商品到商品列表
    async add() {
      console.log('原先的数据', this.goods)
      this.$refs['add'].validate(async (valid) => {
        if (valid) {
          // 将数组转为字符串
          this.goods.goods_cat = this.goods.goods_cat.join(',')
          // 处理动态数据
          const dong = this.dongziyu.map((item) => {
            return {
              attr_id: item.attr_id,
              attr_value: item.attr_vals.join(',')
            }
          })
          // 处理静态数据
          const jing = this.jingtaiziyuan.map((item) => {
            return {
              attr_id: item.attr_id,
              attr_value: item.attr_vals
            }
          })
          this.goods.attrs = [...dong, ...jing]
          console.log('处理后的数据', this.goods)
          const res = await this.$API.addgoods(this.goods)
          console.log('这是添加的数据', res)
          this.$router.push('/goods')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  },
  computed: {
    cateid() {
      console.log(
        '分类id',
        this.goods.goods_cat[this.goods.goods_cat.length - 1]
      )
      return this.goods.goods_cat[this.goods.goods_cat.length - 1]
    }
  }
}
</script>

<style lang="scss" scoped>
.home {
  width: 100%;
  ::v-deep .el-step__title {
    font-size: 13px;
  }
  ::v-deep .ql-editor {
    height: 300px;
  }
}
</style>
